package com.hzw.video.decoder

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.hzw.video.extractor.IExtractor
import com.hzw.video.extractor.VideoExtractor
import java.nio.ByteBuffer

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/9/16 9:49
 *
 * @Description:
 *
 */
class VideoDecoder(
    path: String,
    val surfaceView: SurfaceView?,
    var surface: Surface?
) : BaseDecoder(path) {

    companion object {
        const val TAG = "VideoDecoder"
    }

    override fun check(): Boolean {
        if (surfaceView == null && surface == null) {
            Log.e(TAG, "SurfaceView和Surface都为空，至少需要一个不为空")
            stateListener?.decoderError(this, "SurfaceView和Surface都为空，至少需要一个不为空")
            return false
        }
        return true
    }

    override fun initExtractor(filePath: String): IExtractor {
        return VideoExtractor(filePath)
    }

    override fun initSpecParams(format: MediaFormat) {

    }

    override fun initRender(): Boolean {
        return true
    }

    override fun configCodec(mediaCodec: MediaCodec, format: MediaFormat): Boolean {
        if (surface != null) {
            mediaCodec.configure(format, surface, null, 0)
            notifyDecode()
        } else {
            surfaceView?.holder?.addCallback(object : SurfaceHolder.Callback2 {
                override fun surfaceCreated(holder: SurfaceHolder?) {
                    surface = holder?.surface
                    configCodec(mediaCodec, format)
                }

                override fun surfaceChanged(
                    holder: SurfaceHolder?,
                    format: Int,
                    width: Int,
                    height: Int
                ) {

                }

                override fun surfaceDestroyed(holder: SurfaceHolder?) {

                }

                override fun surfaceRedrawNeeded(holder: SurfaceHolder?) {

                }

            })
            return false
        }
        return true
    }

    override fun render(byteBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) {

    }

    override fun doneDecode() {

    }

    override fun pause() {

    }

    override fun goOn() {

    }

    override fun stop() {
        extractor?.stop()
    }

    override fun isDecoding(): Boolean {
        return isRunning
    }

    override fun isSeeking(): Boolean {
        return isRunning
    }

    override fun isStop(): Boolean {
        return isRunning
    }

    override fun getWidth(): Int {
        return videoWidth
    }

    override fun getHeight(): Int {
        return videoHeight
    }

    override fun getRotationAngle(): Int {
        return 0
    }

    override fun getMediaFormat(): MediaFormat? {
        return extractor?.getFormat()
    }

    override fun getTrack(): Int {
        return extractor?.getTrack() ?: 0
    }
}